package com.personal.o2o.util;

import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.BarcodeSettings;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CODE_128 {

    /**
     * 条形码宽度
     */
    private static final float WIDTH = 300f;

    /**
     * 条形码高度
     */
    private static final float HEIGHT = 50f;

    /**
     * 加文字 条形码
     */
    private static final int WORDHEIGHT = 175;

    public static void main(String[] args) throws IOException {
        // 1.生成关键字的条形码
        BufferedImage bufferedImage = getBarCode("97352617844");
        // 2.将条码图片生成到画板中并加上描述
        String[] strs = {"Maybelline Foundation","新品","MADE IN CHINA"};
        BufferedImage image = insertWords(bufferedImage, strs);
        // 3.保存图像
        ImageIO.write(image, "png", new File("/Users/chenhao/Downloads/QQ文件/CODE_128.png"));

//        scanningBarcode();
    }

    /**
     * 生成条形码图片缓冲
     * @param keyStr  条形码关键字
     * @return 返回BufferedImage
     */
    public static BufferedImage getBarCode(String keyStr){
        //创建BarcodeSettings
        BarcodeSettings settings = new BarcodeSettings();
        //设置图片宽度
//        settings.setImageWidth(WIDTH);
        //设置图片高度
//        settings.setImageHeight(HEIGHT);
        //设置条形码数据
        settings.setData(keyStr);
        //设置符号属性
        settings.setType(BarCodeType.CODE_128);
        //在底部设置显示文本位置
        settings.setShowTextOnBottom(true);
        //设置边界可见
        settings.hasBorder(false);
        //创建条形码生成器实例
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //从条形码生成器获取图像
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //保存图像
        //ImageIO.write(bufferedImage, "png", new File("/Users/chenhao/Downloads/QQ文件/CODE_128.png"));
        return bufferedImage;
    }

    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image 条形码图片
     * @param words 文字
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage insertWords(BufferedImage image, String[] words) {
        // 新的图片，把带logo的二维码下面加上文字
        if (!StringUtils.isEmpty(words)) {

            BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight()+80, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = outImage.createGraphics();

            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);

            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            for (int s=1;s<words.length+1;s++){
                //文字长度
                int strWidth = g2d.getFontMetrics().stringWidth(words[s-1]);
                //总长度减去文字长度的一半  （居中显示）
                int wordStartX = (image.getWidth() - strWidth) / 2;
                //height + (outImage.getHeight() - height) / 2 + 12
                int wordStartY = image.getHeight() + 20*s;
                // 画文字
                g2d.drawString(words[s-1], wordStartX, wordStartY);
            }
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     * @param g2d  Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d){
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d){
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0,0,600,600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    /**
     * 可查看打印机
     */
    public static void setPrint() {
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
        for (int i = 0; i < printService.length; i++) {
            String printName = printService[i].getName();
            System.out.println(printName);
        }

        PrintService PS = PrintServiceLookup.lookupDefaultPrintService();
        String printName = PS.getName();
        System.out.println("当前默认打印机为:" + printName);
        System.out.println("如果不争取请在控制面板设置默认打印机");

    }

    /**
     * 扫描条码显示信息
     * @throws Exception
     */
    public static void scanningBarcode() {
        //从要扫描的图像中获取信息
        String[] s= new String[0];
        try {
            s = BarcodeScanner.scan("/Users/chenhao/Downloads/QQ文件/CODE_128.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i=0;i< s.length ;i++){
            System.out.println(s[i]);
        }
    }


}
